package com.example.websocket3.comfig;

import com.example.websocket3.entity.User;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.security.Principal;
import java.util.List;
import java.util.Map;

/** 通道拦截器*/
public class MyChannelInterceptor implements ChannelInterceptor {

    private User mydlq1 = new User("","123456-1");

    private User mydlq2 = new User("","123456-2");

    /**  检验token，区分用户 */
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);   // STOMP消息头
        String token = getToken(message);
        if(token != null && accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())){
            Principal user = null;
            if(mydlq1.getToken().equals(token)){
                user = () -> mydlq1.getUsername();
            }else if(mydlq2.getToken().equals(token)){
                user = () -> mydlq2.getUsername();
            }
            accessor.setUser(user);
        }
        return message;
    }


    private String getToken(Message<?> message){
        Map<String,Object> headers =(Map<String, Object>) message.getHeaders().get("nativeHeaders");
        if(headers != null && headers.containsKey("token")){
            List<String> token = (List<String>) headers.get("token");
            System.out.println("---------token="+token.get(0));
            return String.valueOf(token.get(0));
        }
        return null;
    }
}
